# -*- encoding: utf-8 -*-
"""
@Project : AIGateWay 
@FileName: async_handler
@Time    : 2020/11/26 14:59
@Author  : chenych
@Desc    :
"""
import ailog
from Client.asyn_request import AsynClient
from util.img_down import img_download
import json
from Core import SYS_CODE
from Core import conf
from util.check_resp_util import RespException,asyn_check_resp


class CameraInspectTask():
    asynClient = AsynClient()

    url_host = conf.get('pic_ability_url', 'host_pic')
    url_port = conf.get('pic_ability_url', 'port_pic')
    url_picQuaDetection = 'http://{}:{}{}'.format(url_host, url_port, conf.get('pic_ability_url', 'url_picQuaDetection'))

    # 01模糊, 02偏色, 03雪花, 04过曝, 05遮挡, 06条纹

    map_dict = {
        'blur':'01',
        'colorShift': '02',
        'noise': '03',
        'overExposure': '04',
        'shelter': '05',
        'stripe': '06',

    }


    @classmethod
    @asyn_check_resp(success_code=SYS_CODE.STATUS.YITU_SUCCESS,code_name='code',msg_name='message')
    async def __check_image(cls, imageBase64s, algs):

        data = {'imageContent': imageBase64s,
                'algs': algs}

        header = {'Content-type': 'application/json'}


        res = await cls.asynClient.post(url=cls.url_picQuaDetection, body=json.dumps(data),header=header)

        res = json.loads(res)
        ailog.debug(res)
        return res

    @staticmethod
    def __build_resp(seqid, code, message, flag, data):

        resp_dict = {

            'seqid': seqid,
            'code': code,
            'message': message,
            'flag': flag,
            'data': data
        }

        return resp_dict

    @classmethod
    async def run(cls, param):

        seqid = param['seqid']

        try:
            deviceId = param['deviceId']
            fileurl = param['fileurl']

        except Exception as e:

            ailog.error('缺少参数：{}'.format(e))

            resp_dict = cls.__build_resp(seqid=seqid,
                                         code=SYS_CODE.RESPCODE.KEYERROR,
                                         message=SYS_CODE.RESPCODE.get_msg(SYS_CODE.RESPCODE.KEYERROR),
                                         flag=SYS_CODE.RESPCODE.FLAG_FAIL,
                                         data={})

            return resp_dict

        try:

            imageBase64s = await img_download(seqid=seqid,img_url=fileurl)

        except Exception as e:

            ailog.error('图片拉取失败：{}'.format(e))
            resp_dict = cls.__build_resp(seqid=seqid,
                                         code=SYS_CODE.RESPCODE.IMAGE_ERROR,
                                         message=SYS_CODE.RESPCODE.get_msg(SYS_CODE.RESPCODE.IMAGE_ERROR),
                                         flag=SYS_CODE.RESPCODE.FLAG_FAIL,
                                         data={})

            return resp_dict

        try:

            algs = ["blur", "colorShift", "overExposure", "shelter", "noise", "stripe"]

            res = await cls.__check_image(imageBase64s, algs)


            detectResult = res['detectResult']


            check_res= [cls.map_dict.get(k,'') for k,v in dict(detectResult).items() if int(v)==1]

            data ={
                    "unqualified ":','.join(check_res)
            }

            resp_dict = cls.__build_resp(seqid=seqid,
                                         code=SYS_CODE.RESPCODE.SUCCESS,
                                         message=SYS_CODE.RESPCODE.get_msg(SYS_CODE.RESPCODE.SUCCESS),
                                         flag=SYS_CODE.RESPCODE.FLAG_SUCCESS,
                                         data=data)

            return resp_dict


        except RespException as er:

            ailog.error('resp error : {}'.format(er))

            resp_dict = cls.__build_resp(seqid=seqid,
                                         code=er.code,
                                         message=er.msg,
                                         flag=SYS_CODE.RESPCODE.FLAG_FAIL,
                                         data={})

            return resp_dict


        except Exception as e:

            ailog.error('error : {}'.format(e))

            resp_dict = cls.__build_resp(seqid=seqid,
                                         code=SYS_CODE.RESPCODE.FAIL,
                                         message=SYS_CODE.RESPCODE.get_msg(SYS_CODE.RESPCODE.FAIL),
                                         flag=SYS_CODE.RESPCODE.FLAG_FAIL,
                                         data={})

            return resp_dict
